/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.andronicus.simplifiedrecyclerviewexample.util;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.TabList;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * ResUtil.
 */
public class ResUtil {
    private static final String TAG = "ResUtil";
    private static Map<Integer, PixelMap> imageCache = new HashMap();
    private ResUtil() {
    }

    /**
     * get the Element
     *
     * @param color the color
     * @return the Element
     */
    public static Element buildDrawableByColor(int color) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(RgbColor.fromArgbInt(color));
        return drawable;
    }

    /**
     * get the Element
     *
     * @param inside the inside color
     * @param rect Rect
     * @return element
     */
    public static Element getCustomRectGradientDrawable(Color inside, Rect rect) {
        ShapeElement element = new ShapeElement();
        element.setShape(ShapeElement.RECTANGLE);
        element.setRgbColor(RgbColor.fromArgbInt(inside.getValue()));
        element.setBounds(rect);
        return element;
    }

    /**
     * get createTabIcon Element
     *
     * @param abilitySlice AbilitySlice
     * @param tab          Tablist
     * @param ival         Integer
     */
    public static void createTabIcon(AbilitySlice abilitySlice, TabList.Tab tab, int ival) {
        if (tab == null) {
            LogUtil.debug(TAG, "createTabIcon failed");
            return;
        }
        try {
            PixelMap pixelMap = createByResourceId(abilitySlice, ival, "image/png");
            PixelMapElement pixelMapElement = new PixelMapElement(pixelMap);
            pixelMapElement.setBounds(0, 0, Const.FIFTY, Const.FIFTY);
            tab.setAroundElements(pixelMapElement, null, null, null);
            tab.setPadding(Const.THIRTY, 0, 0, 0);
        } catch (NotExistException | IOException e) {
            LogUtil.debug(TAG, "createTabIcon " + e.getLocalizedMessage());
        }
    }

    /**
     * get createByResourceId Element
     *
     * @param abilitySlice AbilitySlice
     * @param ivalue integer
     * @param str String
     * @return pixelMap pixelmap
     * @throws IOException exception
     * @throws NotExistException exception
     */
    public static PixelMap createByResourceId(AbilitySlice abilitySlice, int ivalue, String str)
            throws IOException, NotExistException {
        if (imageCache.containsKey(Integer.valueOf(ivalue))) {
            return imageCache.get(Integer.valueOf(ivalue));
        } else {
            ResourceManager resourceManager = abilitySlice.getResourceManager();
            if (resourceManager != null) {
                Resource resource = resourceManager.getResource(ivalue);
                if (resource != null) {
                    ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
                    sourceOptions.formatHint = str;
                    ImageSource create = ImageSource.create(readResource(resource), sourceOptions);
                    resource.close();
                    if (create != null) {
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        decodingOptions.desiredSize = new Size(0, 0);
                        decodingOptions.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0);
                        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                        PixelMap pixelMap = create.createPixelmap(decodingOptions);
                        imageCache.put(Integer.valueOf(ivalue), pixelMap);
                        return pixelMap;
                    }
                    LogUtil.debug(TAG, "imageSource is null");
                    throw new FileNotFoundException();
                }
                LogUtil.debug(TAG, "get resource failed");
                throw new IOException();
            }
            LogUtil.debug(TAG, "get resource manager failed");
            throw new IOException();
        }
    }

    /**
     * get readResource bytes
     *
     * @param resource Resource
     * @return pixelMap pixelmap
     */
    private static byte[] readResource(Resource resource) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] barr = new byte[Const.TEN_TWNTY4];
        while (true) {
            try {
                int read = resource.read(barr, 0, Const.TEN_TWNTY4);
                if (read == Const.MINUS_ONE) {
                    break;
                }
                byteArrayOutputStream.write(barr, 0, read);
            } catch (IOException e) {
                LogUtil.debug(TAG, "readResource failed " + e.getLocalizedMessage());
            }
        }
        LogUtil.debug(TAG, "readResource finish");
        LogUtil.debug(TAG, "readResource len: " + byteArrayOutputStream.size());
        return byteArrayOutputStream.toByteArray();
    }
}

